import { createStore, Store, useStore as baseUseStore } from 'vuex'

import { InjectionKey } from 'vue'

import { UserMoudleTypes } from './modules/user'

const files = import.meta.globEager('./modules/*.ts')
const modules: { [propName: string]: any } = {}
Object.keys(files).map(async (key) => {
  const module = files[key]
  const name = key.replace('./modules/', '').replace('.ts', '')
  modules[name] = module.default
})

export interface RootStateTypes {
  count: number;
  userInfo: {
    displayName: string
  };
}
export interface AllStateTypes extends RootStateTypes {
  user: UserMoudleTypes;
}

export const key: InjectionKey<Store<RootStateTypes>> = Symbol('store')

export default createStore<RootStateTypes>({
  modules,
  state () {
    return {
      count: 0,
      userInfo: {}
    }
  },
  mutations: {
    increment (state) {
      state.count++
    },
    changeInfo (state, obj: RootStateTypes['userInfo']) {
      state.userInfo = {
        ...state.userInfo,
        ...obj
      }
    }
  }
})

// define your own `useStore` composition function
export function useStore<T = AllStateTypes> () {
  return baseUseStore<T>(key)
}
